<template>
  <div style="width:80%;">
    <el-upload
      :before-upload="handleChange"
      :file-list="fileList"
      :limit="props['limit']"
    >
      <el-button slot="trigger" size="small" type="primary">选取文件</el-button>
    </el-upload>
  </div>
</template>

<script lang="ts" setup>

import { ref } from 'vue'
import { md5 } from 'js-md5'
import COS from 'cos-js-sdk-v5'
import { getTencentToken } from '@/api/tencent'

// eslint-disable-next-line vue/require-prop-types
const props = defineProps(['pathPrefix', 'limit', 'uploadList'])

const emit = defineEmits(['uploadFile'])

const fileList = ref([])

const handleChange = async(file) => {
  // 获取当前日期做目录
  const currentDate = new Date()
  const currentYear = currentDate.getFullYear()
  const currentMonth = currentDate.getMonth() + 1
  const currentDay = currentDate.getDate()
  const dateDir = `/${currentYear}/${currentMonth}/${currentDay}`
  // 获取随机数
  const number = Math.floor(Math.random() * (999999 - 100000 + 1)) + 100000

  const pathPrefix = props.pathPrefix + dateDir

  // 名称md5加密
  const [prefixName, suffix] = file.name.split('.')
  const name = md5(prefixName) + '.' + suffix

  // 在上传之前设置文件名
  const filename = pathPrefix + `/${Date.now()}_${number}_${name}`

  const tokenData = await getTencentToken({ pathPrefix: props.pathPrefix })
  console.log(tokenData)

  const cos = new COS({
    getAuthorization: function(options, callback) {
      callback({
        TmpSecretId: tokenData.data.tmpSecretId,
        TmpSecretKey: tokenData.data.tmpSecretKey,
        SecurityToken: tokenData.data.token,
        ExpiredTime: tokenData.data.expiredTime,
        StartTime: tokenData.data.startTime,
      })
    },
  })

  const params = {
    Bucket: tokenData.data.bucket,
    Region: tokenData.data.region,
    Key: filename,
    Body: file, // 这是一个 File 对象，通常来自 <input type="file">
  }

  try {
    const response = await cos.putObject(params)
    if (response.statusCode === 200) {
      // 上传完成的处理
      fileList.value[0] = {
        name: filename,
        url: tokenData.data.domain + filename,
      }

      // 上传成功，将文件传回父组件
      await uploadFile(fileList.value)
    }
  } catch (error) {
    console.error('上传失败:', error)
  }
  return false
}

const uploadFile = async(fileList) => {
  emit('uploadFile', fileList)
}

</script>
